package ljl.alg.wangzheng_camp.round1.find_the_law;

import java.util.HashMap;
import java.util.Map;

public class _16_15_master_mind {
    
    /**
     * 我思路可能有点笨啊
     * 先遍历一次，记录猜中次数
     * 标记数组，标记猜中位置
     * 搞个 map，记录其它的情况，然后比较，计数
     *
     * 写了这么长，这是简单吗
     *
     * 好在通过了
     * */
    public int[] masterMind2(String solution, String guess) {
        boolean[] visited = new boolean[4];
        int bingo = 0, sudoBingo = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < 4; i++) {
            if (solution.charAt(i) == guess.charAt(i)) {
                visited[i] = true;
                bingo++;
            }
            else {
                char c = solution.charAt(i);
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
        }
        for (int i = 0; i < 4; i++) {
            if (!visited[i]) {
                char c = guess.charAt(i);
                if (map.containsKey(c)) {
                    sudoBingo++;
                    int count = map.get(c);
                    if (count == 1) {
                        map.remove(c);
                    } else {
                        map.put(c, count - 1);
                    }
                }
            }
        }
        
        return new int[] {bingo, sudoBingo};
    }
    
    /**
     * 还有一点点优化的空间
     * 不需要那个数组，做差就行了
     *
     * 我这是优化了个寂寞啊还是这么长
     *
     * 尽力了 再优化没法看了
     * */
    public int[] masterMind(String solution, String guess) {
        int bingo = 0, sudoBingo = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < 4; i++) {
            char c = solution.charAt(i);
            if (c == guess.charAt(i)) {
                bingo++;
            }
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < 4; i++) {
            char c = guess.charAt(i);
            if (map.containsKey(c) && map.get(c) > 0) {
                sudoBingo++;
                map.put(c, map.get(c) - 1);
            }
        }
    
        return new int[]{bingo, sudoBingo - bingo};
    }
}
